<?php

declare(strict_types=1);

namespace app\admin\controller;

use app\BaseController;
use app\common\model\Order\Order as OrderModel;
use app\common\model\Order\Product as ProductModel;
use app\common\model\Product\Express as ExpressModel;
use app\common\model\Product\Product;
use app\common\model\User\Record as RecordModel;
use app\common\model\User\User as UserModel;
use app\common\validate\User\Record as RecordValidate;
use Exception;
use think\exception\ValidateException;

class Order extends BaseController
{
    protected $middleware = [
        \app\admin\middleware\LoginAuth::class
    ];
    public function index()
    {
        $menu = [
            'name' => '订单管理',
            'title' => '订单列表'
        ];
        $searchfield = $this->request->param('search_field', 'code');
        $keyword = $this->request->param('keyword');
        $where = [];
        if ($searchfield && $keyword) {
            $where[] = [$searchfield, 'like', "$keyword"];
        }
        $num = 8;
        $OrderList = OrderModel::with(['user', 'express'])->order('createtime', 'desc')->where($where)->paginate(['list_rows' => $num, 'query' => request()->param()]);
        // 当前页
        $page = $OrderList->currentPage();
        return view('', [
            'menu' => $menu,
            'OrderList' => $OrderList,
            'num' => $num,
            'page' => $page
        ]);
    }
    // 异步请求配送公司数据
    public function express()
    {
        $action = $this->request->param('action');
        $orderid = $this->request->param('orderid');
        if ($action == 'expre') {
            $Order = OrderModel::with(['express'])->find($orderid);
            $this->success('查询成功', null, $Order);
        } else {
            $Express = ExpressModel::select();
            $this->success('查询成功', null, $Express);
        }
    }
    // 发货 && 修改配送信息
    public function delivery()
    {
        // 订单号
        $expcode = $this->request->param('expcode');
        // 订单id
        $orderid = $this->request->param('orderid');
        // 配送公司
        $express = $this->request->param('selected');
        $action = $this->request->param('action');
        $Order = OrderModel::find($orderid);
        if (!$Order) {
            $this->error('订单不存在');
        }
        $Express = ExpressModel::find($express);
        if (!$Express) {
            $this->error('请选择有效的配送方式');
        }
        if (empty($expcode)) {
            $this->error('配送单号不能为空');
        }
        $data = [
            'expid' => $express,
            'expcode' => $expcode
        ];
        if ($action == 'edit') {
            $result = OrderModel::where(['id' => $Order['id']])->update($data);
            if ($result === FALSE) {
                $this->error('修改失败');
            }
            $this->success('修改成功');
        } else {
            $data['status']=2;
            $result = OrderModel::update($data, ['id' => $Order['id']]);
            if ($result === FALSE) {
                $this->error('发货失败');
            }
            $this->success('发货成功');
        }
    }
    // 查看订单
    public function info()
    {
        $menu = [
            'name' => '订单管理',
            'title' => '订单详情'
        ];
        $orderid = $this->request->param('orderid');
        $Order = OrderModel::with(['user', 'address'])->find($orderid);
        if (!$Order) {
            $this->error('订单不存在');
        }
        $ProductList = ProductModel::with(['products'])->where(['orderid' => $orderid])->select();
        if (count($ProductList) <= 0) {
            $this->error('订单商品不存在');
        }
        return view('', [
            'menu' => $menu,
            'Order' => $Order,
            'ProductList' => $ProductList,
        ]);
    }
    // 查看物流
    public function logistics()
    {
        $menu = [
            'name' => '订单管理',
            'title' => '查看物流'
        ];
        $orderid = $this->request->param('orderid');
        $Order = OrderModel::with(['express'])->find($orderid);
        if (!$Order) {
            $this->error('订单不存在');
        }
        return view('', [
            'menu' => $menu,
            'Order' => $Order,
        ]);
    }
    // 删除订单
    public function del()
    {
        $orderid = $this->request->param('orderid');
        $ids = $this->request->param('ids');
        $action = $this->request->param('action');
        try {
            OrderModel::startTrans();
            ProductModel::startTrans();
            if ($action == 'del') {
                $Order = OrderModel::find($orderid);
                if (!$Order) {
                    throw new Exception('订单不存在！请重新选择');
                }
                $ProductList = ProductModel::where(['orderid' => $orderid])->select();
                // $ProductList = ProductModel::where(['orderid' => $orderid])->fetchSql()->select();
                if (count($ProductList) <= 0) {
                    throw new Exception('订单商品不存在');
                }
                foreach ($ProductList as $key => $item) {
                    $res = ProductModel::destroy($item['id']);
                    if ($res === FALSE) {
                        throw new Exception('删除订单商品失败！');
                    }
                }
                $result = OrderModel::destroy($orderid);
                if ($result === FALSE) {
                    throw new Exception('删除订单失败！');
                }
            }
            // 批量删除
            if ($action == 'dels') {
                $OrderList = OrderModel::whereIn('id', $ids)->select();
                foreach ($OrderList as $key => $item) {
                    if (!in_array($item['id'], $ids)) {
                        throw new Exception('所选的订单不存在！请重新选择');
                    }
                    // 批量删除订单商品
                    $ProductList = ProductModel::where(['orderid' => $item['id']])->select();
                    if (count($ProductList) <= 0) {
                        throw new Exception('订单商品不存在');
                    }
                    foreach ($ProductList as $key => $item) {
                        $res = ProductModel::destroy($item['id']);
                        if ($res === FALSE) {
                            throw new Exception('批量删除订单商品失败！');
                        }
                    }
                }
                $result = OrderModel::destroy($ids);
                if ($result === FALSE) {
                    throw new Exception('批量删除失败！');
                }
            }
        } catch (Exception $error) {
            OrderModel::rollback();
            ProductModel::rollback();
            $this->error($error->getMessage());
        }
        OrderModel::commit();
        ProductModel::commit();
        $this->success('删除成功');
    }
    // 回收站
    public function recycle()
    {
        $menu = [
            'name' => '订单管理',
            'title' => '订单回收站'
        ];
        $searchfield = $this->request->param('search_field', 'code');
        $keyword = $this->request->param('keyword');
        $where = [];
        if ($searchfield && $keyword) {
            $where[] = [$searchfield, 'like', "$keyword"];
        }
        $num = 8;
        $OrderList = OrderModel::onlyTrashed()->with(['user', 'express'])->order('createtime', 'desc')->where($where)->paginate(['list_rows' => $num, 'query' => request()->param()]);
        // 当前页
        $page = $OrderList->currentPage();
        return view('', [
            'menu' => $menu,
            'OrderList' => $OrderList,
            'num' => $num,
            'page' => $page
        ]);
    }
    // 恢复
    public function recovery()
    {
        $orderid = $this->request->param('orderid');
        $ids = $this->request->param('ids');
        $action = $this->request->param('action');
        try {
            OrderModel::startTrans();
            ProductModel::startTrans();
            // 单条恢复
            if ($action == 'adopt') {
                $Order = OrderModel::onlyTrashed()->find($orderid);
                if (!$Order) {
                    throw new Exception('订单不存在！请重新选择');
                }
                // 恢复订单商品
                $ProductList = ProductModel::onlyTrashed()->where(['orderid' => $orderid])->select();
                if (count($ProductList) <= 0) {
                    throw new Exception('订单商品不存在');
                }
                foreach ($ProductList as $key => $item) {
                    $res = ProductModel::onlyTrashed()->where(['id' => $item['id']])->update(['deletetime' => null]);
                    if ($res === FALSE) {
                        throw new Exception('恢复订单商品失败！');
                    }
                }
                // 恢复订单
                $result = $Order->restore();
                if ($result === FALSE) {
                    throw new Exception('恢复失败！');
                }
            }
            // 批量恢复
            if ($action == 'adopts') {
                $OrderList = OrderModel::onlyTrashed()->whereIn('id', $ids)->select();
                foreach ($OrderList as $key => $item) {
                    if (!in_array($item['id'], $ids)) {
                        throw new Exception('所选的订单不存在！请重新选择');
                    }
                    // 批量恢复订单商品
                    $ProductList = ProductModel::onlyTrashed()->where(['orderid' => $item['id']])->select();
                    if (count($ProductList) <= 0) {
                        throw new Exception('订单商品不存在');
                    }
                    foreach ($ProductList as $key => $value) {
                        $res = ProductModel::onlyTrashed()->where(['id' => $value['id']])->update(['deletetime' => null]);
                        if ($res === FALSE) {
                            throw new Exception('恢复订单商品失败！');
                        }
                    }
                }
                // 批量恢复订单
                $result = OrderModel::onlyTrashed()->where(['id' => $ids])->update(['deletetime' => null]);
                if ($result === FALSE) {
                    throw new Exception('批量恢复失败！');
                }
            }
        } catch (Exception $error) {
            OrderModel::rollback();
            ProductModel::rollback();
            $this->error($error->getMessage());
        }
        OrderModel::commit();
        ProductModel::commit();
        $this->success('恢复成功');
    }
    // 同意退货
    public function agree()
    {
        try {
            $orderid = $this->request->param('orderid');
            // 查询订单是否存在
            $Order = OrderModel::where(['id' => $orderid])->find();
            if (!$Order) {
                throw new \Exception('订单不存在');
            }
            // 查询用户是否存在
            $User = UserModel::find($Order['userid']);
            if (!$User) {
                throw new \Exception('用户不存在');
            }
            // 查询订单商品数据
            $ProductList = ProductModel::where(['orderid' => $orderid])->select();

            // 开启事务
            OrderModel::startTrans();
            ProductModel::startTrans();
            UserModel::startTrans();
            RecordModel::startTrans();
            Product::startTrans();

            $Order->status = -1;
            $OrderStatus = $Order->save();
            if ($OrderStatus === FALSE) {
                throw new \Exception('更改订单状态失败');
            }
            foreach ($ProductList as $key => $item) {
                $Product = Product::where(['id' => $item['proid']])->find();
                $Product->stock = bcadd((string)$Product['stock'], (string)$item['nums']);
                $ProductStatus = $Product->save();
                if ($ProductStatus === FALSE) {
                    throw new \Exception('更新商品库存失败');
                }
            }
            $User->point = bcadd((string)$Order['total'], (string)$User['point']);
            $UserStatus = $User->save();
            if ($UserStatus === FALSE) {
                throw new \Exception('更新用户积分失败');
            }
            // 新增消费记录
            $RecordData = [
                'point' => $Order['total'],
                'content' => "您的订单{$Order['code']}退货成功，{$Order['total']}积分已退回您的账户",
                'state' => -1,
                'userid' => $User['id']
            ];
            // var_dump($RecordData);
            // exit;
            // 验证数据
            validate(RecordValidate::class)->check($RecordData);
            // 新增
            $RecordStatus = RecordModel::create($RecordData);
            // 判断是否成功
            if ($RecordStatus === FALSE) {
                throw new \Exception('新增消费记录失败');
            }
        } catch (ValidateException $e) {
            OrderModel::rollback();
            Product::rollback();
            UserModel::rollback();
            RecordModel::rollback();
            ProductModel::rollback();
            $this->error($e->getError());
        } catch (\Exception $error) {
            OrderModel::rollback();
            Product::rollback();
            UserModel::rollback();
            RecordModel::rollback();
            ProductModel::rollback();
            $this->error($error->getMessage());
        }
        OrderModel::commit();
        Product::commit();
        UserModel::commit();
        RecordModel::commit();
        ProductModel::commit();

        $this->success('同意退货成功');
    }
    public function refuse(){
        $orderid = $this->request->param('orderid');
            // 查询订单是否存在
            $Order = OrderModel::where(['id' => $orderid])->find();
            if (!$Order) {
                $this->error('订单不存在');
            }
            // 查询用户是否存在
            $User = UserModel::find($Order['userid']);
            if (!$User) {
                $this->error('用户不存在');
            }
            $Order->status = -3;
            $OrderStatus = $Order->save();
            if ($OrderStatus === FALSE) {
                $this->error('更改订单状态失败');
            }
            $this->success('拒绝退货成功！');
    }
}
